import { _decorator, Component, Collider2D, Contact2DType, PhysicsSystem2D, IPhysics2DContact, BoxCollider, BoxCollider2D } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EnemyControl')
export class EnemyControl extends Component {
    @property
    speed: number = 100;
    @property
    hp: number = 1;

    collider: Collider2D = null;
    start() {
        //注册单个碰撞体的回调函数
        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        this.hp -= 1;
        //触发碰撞以后，禁用collider2d组件
        if(this.collider){
            this.collider.enabled = false;
        }
        if(this.hp <= 0){
            setTimeout(() => {
                this.node.destroy();
            } , 0)
        }
    }
    
    update(deltaTime: number) {
        if (this.hp > 0) {
            const enemyPos = this.node.position;
            let targetposY = enemyPos.y - this.speed * deltaTime;
            this.node.setPosition(enemyPos.x, targetposY, enemyPos.z);
            if (targetposY < -1100) {
                this.node.destroy();
            }
        }   
    }
    //节点摧毁时记得注销
    protected onDestroy(): void {
        if(this.collider){
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }
}

